package com.lmx.persistence.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.lmx.repoDomain.tmodel.Dicttype;
import com.lmx.repoDomain.tmodel.HealthAnalysis;

import io.katharsis.queryParams.QueryParams;

/**
 * 健康分析
 * 
 * @author ytche
 * @date 2017年4月28日
 * 
 */
@Service
public class HealthAnalysisService {

	@PersistenceContext
	private EntityManager em;

	@Autowired
	private GenericService<HealthAnalysis> dslJpaService;
	@Autowired
	private DicttypeService dicSrv;

	/**
	 * findALL
	 * 
	 * @author ytche
	 * @param requestParams
	 * @return
	 * @date 2017年4月28日 上午10:51:12
	 */
	public Iterable<HealthAnalysis> findAll(QueryParams requestParams, Long customerId) {
		int limit = 1;// 每个类型限制条数
		List<HealthAnalysis> list = Lists.newArrayList();
		List<Dicttype> types = this.dicSrv.findByGroupCode("healthExamType");
		if (types == null || types.size() <= 0) {
			return list;
		}
		// 根据获取的健康类型拼sql,取每个类型的前n条数据
		String sql = "";
		Integer[] paramArray = new Integer[types.size()];
		for (int i = 0; i < types.size(); i++) {
			if (i > 0) {
				sql += " UNION ";
			}
			sql += "( SELECT * FROM health_analysis WHERE customer_id=" + customerId + " AND  type_id = ?" + (i + 1)
					+ " ORDER BY create_time LIMIT " + limit + "  )";
			paramArray[i] = types.get(i).getId().intValue();
		}

		Query query = this.em.createNativeQuery(sql, HealthAnalysis.class);

		for (int i = 0; i < paramArray.length; i++) {
			query.setParameter(i + 1, paramArray[i]);
		}
		return query.getResultList();
	}

}
